package com.example.choupaiapp.main.fragment.find;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.choupaiapp.R;
import com.example.choupaiapp.common.constant.Contacts;
import com.example.choupaiapp.common.finalokgo.callback.Callback;
import com.example.choupaiapp.common.finalokgo.request.RequestType;
import com.example.choupaiapp.common.ui.fragment.CommonFragment;
import com.example.choupaiapp.common.util.SharedPreferencesHelp;
import com.example.choupaiapp.main.adapter.FindChildAdapter;
import com.example.choupaiapp.main.bean.FindListBean;
import com.example.choupaiapp.main.bean.UserInfoBean;
import com.example.choupaiapp.main.constant.Url;
import com.example.choupaiapp.main.util.jpush.ExampleUtil;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.orhanobut.logger.Logger;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.jpush.android.api.JPushInterface;

/**
 * Created by ASUS on 2019/11/21.
 */

public class FindChildFragment extends CommonFragment implements OnRefreshLoadMoreListener {

    Unbinder unbinder;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private String tabId;
    public int data = 0;
    private UserInfoBean mUserInfoBean;
    private FindChildAdapter findChildAdapter;
    private List<FindListBean.ListBean> listBeans = new ArrayList<>();

    public static FindChildFragment newInstance(String tabId) {
        FindChildFragment findChildFragment = new FindChildFragment();
        findChildFragment.tabId = tabId;
        return findChildFragment;
    }

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_find_child, container, false);
        unbinder = ButterKnife.bind(this, view);

        EventBus.getDefault().register(this);

        mUserInfoBean = (UserInfoBean) SharedPreferencesHelp.getBean("userInfo");

        refreshLayout.setOnRefreshLoadMoreListener(this);
        refreshLayout.setEnableRefresh(false);
        refreshLayout.setRefreshHeader(new MaterialHeader(context).setColorSchemeResources(R.color.common_color));


        GridLayoutManager layoutManager = new GridLayoutManager(context, 2, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        findChildAdapter = new FindChildAdapter(context, tabId);
        recyclerView.setAdapter(findChildAdapter);

        return view;
    }


    @Override
    protected void initData() {
        showDialog(context, null);
        HttpParams params = new HttpParams();
        params.put("categoriesId", tabId);
        params.put("limit", 10);
        if (mUserInfoBean != null) {
            params.put("userId", mUserInfoBean.getUser().getUserId());
        } else {
            if (!TextUtils.isEmpty(ExampleUtil.getImei(context, ""))) {
                params.put("uuid", ExampleUtil.getImei(context, ""));
            } else {
                if (!TextUtils.isEmpty(JPushInterface.getUdid(context))) {
                    params.put("uuid", JPushInterface.getUdid(context));
                } else {
                    if (!TextUtils.isEmpty(JPushInterface.getRegistrationID(context))) {
                        params.put("uuid", JPushInterface.getRegistrationID(context));
                    } else {
                        params.put("uuid", System.currentTimeMillis() + "");
                    }
                }
            }
        }
        finalOkGo.request(RequestType.POST, Url.FIND_LIST, params, Url.FIND_LIST, new Callback<FindListBean>() {
            @Override
            public void onSuccess(FindListBean findListBean) {
                dismissDialog();
                if (findListBean.getCode() == Contacts.SUCCESS) {
                    if (findListBean.getList() == null || findListBean.getList().size() == 0) {
                        data = 0;
                    } else {
                        data = 1;
                    }
                    refreshLayout.finishRefresh();
                    findChildAdapter.setNewData(findListBean.getList());
                } else {
                    refreshLayout.finishRefresh();
                    if (findListBean.getCode() == Contacts.TOKEN_EMPTY) {
                    } else {
                        showImageToas(findListBean.getMsg());
                    }
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                refreshLayout.finishRefresh();
                dismissDialog();
            }
        });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        HttpParams params = new HttpParams();
        params.put("categoriesId", tabId);
        try {
            params.put("startTime", findChildAdapter.getListBeans().get(findChildAdapter.getItemCount() - 1).getCreateTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        params.put("limit", 10);
        if (mUserInfoBean != null) {
            params.put("userId", mUserInfoBean.getUser().getUserId());
        } else {
            if (!TextUtils.isEmpty(ExampleUtil.getImei(context, ""))) {
                params.put("uuid", ExampleUtil.getImei(context, ""));
            } else {
                if (!TextUtils.isEmpty(JPushInterface.getUdid(context))) {
                    params.put("uuid", JPushInterface.getUdid(context));
                } else {
                    if (!TextUtils.isEmpty(JPushInterface.getRegistrationID(context))) {
                        params.put("uuid", JPushInterface.getRegistrationID(context));
                    } else {
                        params.put("uuid", System.currentTimeMillis() + "");
                    }
                }
            }
        }
        finalOkGo.request(RequestType.POST, Url.FIND_LIST, params, Url.FIND_LIST, new Callback<FindListBean>() {
            @Override
            public void onSuccess(FindListBean findListBean) {
                if (findListBean.getCode() == Contacts.SUCCESS) {
                    data = 1;
                    if (findListBean.getList() == null || findListBean.getList().size() == 0) {
                        refreshLayout.finishLoadMoreWithNoMoreData();
                    } else {
                        findChildAdapter.addData(findListBean.getList());
                        refreshLayout.finishLoadMore();
                    }
                } else {
                    refreshLayout.finishLoadMore();
                    if (findListBean.getCode() == Contacts.TOKEN_EMPTY) {
                    } else {
                        showImageToas(findListBean.getMsg());
                    }
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                refreshLayout.finishLoadMore();
            }
        });
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        initData();
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void OnMessageEvent(String event) {
        String s = event.split(":")[0];
        if (s.equals("refresh_find_cancel_praise")) {
            findChildAdapter.getListBeans().get(Integer.parseInt(event.split(":")[1])).setIsLike(0);
            findChildAdapter.getListBeans().get(Integer.parseInt(event.split(":")[1])).setLikeSum(findChildAdapter.getListBeans().get(Integer.parseInt(event.split(":")[1])).getLikeSum() - 1);
            findChildAdapter.notifyItemChanged(Integer.parseInt(event.split(":")[1]));
        } else if (s.equals("refresh_find_praise")) {
            findChildAdapter.getListBeans().get(Integer.parseInt(event.split(":")[1])).setIsLike(1);
            findChildAdapter.getListBeans().get(Integer.parseInt(event.split(":")[1])).setLikeSum(findChildAdapter.getListBeans().get(Integer.parseInt(event.split(":")[1])).getLikeSum() + 1);
            findChildAdapter.notifyItemChanged(Integer.parseInt(event.split(":")[1]));
        } else if (s.equals("refresh_find_child")) {
            initData();
        } else if (s.equals("refresh_find_comment_count")) {
            findChildAdapter.getListBeans().get(Integer.parseInt(event.split(":")[1])).setCommentSum(findChildAdapter.getListBeans().get(Integer.parseInt(event.split(":")[1])).getCommentSum() + 1);
            findChildAdapter.notifyItemChanged(Integer.parseInt(event.split(":")[1]));
        } else if (s.equals("delete_find_comment_count")) {
            findChildAdapter.getListBeans().get(Integer.parseInt(event.split(":")[1])).setCommentSum(findChildAdapter.getListBeans().get(Integer.parseInt(event.split(":")[1])).getCommentSum() - 1);
            findChildAdapter.notifyItemChanged(Integer.parseInt(event.split(":")[1]));
        } else if (s.equals("scollTo_find_top")) {
            if (tabId.equals(event.split(":")[1])) {
                recyclerView.scrollToPosition(0);
            }
        } else if (s.equals("refresh_find_data")) {
            if (tabId.equals(event.split(":")[1])) {
                initData();
            }
        }
    }
}
